package com.example.zz.example;

import android.app.Activity;
import android.app.Application;

import android.content.res.Configuration;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.elvishew.xlog.LogConfiguration;
import com.elvishew.xlog.LogLevel;
import com.elvishew.xlog.XLog;
import com.elvishew.xlog.printer.AndroidPrinter;
import com.elvishew.xlog.printer.Printer;
import com.elvishew.xlog.printer.file.FilePrinter;
import com.elvishew.xlog.printer.file.backup.NeverBackupStrategy;
import com.elvishew.xlog.printer.file.naming.DateFileNameGenerator;
import com.example.zz.example.serialization.Device;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.DiskLogAdapter;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.mmkv.MMKV;

/**
 * application生命周期及使用: https://blog.csdn.net/qq_37111698/article/details/104542441
 */
public class App extends Application {

    private WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();

    public WindowManager.LayoutParams getMywmParams() {
        return wmParams;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        //logger框架日志初始化
        initLog();
        //xlog框架日志初始化
        initXLog();

        //全局崩溃捕获初始化，记录到sd卡，并重启应用
//        AppCrashHandler.getInstance().init(this);

        //crash框架捕获后，本地可能不打印崩溃日志了
        CrashReport.initCrashReport(this, "06273dd620", true);

        //mmkv初始化
        mmkvInit();


//        整个app实现默哀黑白模式
//        Paint mPaint = new Paint();
//        ColorMatrix mColorMatrix = new ColorMatrix();
//        mColorMatrix.setSaturation(0);
//        mPaint.setColorFilter(new ColorMatrixColorFilter(mColorMatrix));
//
//        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
//            @Override
//            public void onActivityCreated(Activity activity, Bundle bundle) {
//                // 当Activity创建，我们拿到DecorView，使用Paint进行重绘
//                View decorView = activity.getWindow().getDecorView();
//                decorView.setLayerType(View.LAYER_TYPE_HARDWARE, mPaint);
//            }
//
//            @Override
//            public void onActivityStarted(Activity activity) {
//
//            }
//
//            @Override
//            public void onActivityResumed(Activity activity) {
//
//            }
//
//            @Override
//            public void onActivityPaused(Activity activity) {
//
//            }
//
//            @Override
//            public void onActivityStopped(Activity activity) {
//
//            }
//
//            @Override
//            public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
//
//            }
//
//            @Override
//            public void onActivityDestroyed(Activity activity) {
//
//            }
//        });


    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // 配置改变时触发这个方法。
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        //好的应用程序一般会在这个方法里面释放一些不必要的资源，来应付当后台程序已经终止，前台应用程序内存还不够时的情况。
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        //程序在进行内存清理时执行
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        // 程序终止的时候执行,不保证一定被调用，当程序是被内核终止以便为其他应用程序释放资源，那么将不会提醒，并且不调用应用程序Application对象的onTerminate方法而直接终止进程。
    }

    private void mmkvInit() {
        // MMKV 的根目录（files/mmkv/）
        // /data/user/0/项目包名/files/mmkv
        String rootDir = MMKV.initialize(this);

//        自定义根目录
//        String dir = getFilesDir().getAbsolutePath() + "/mmkv_2";
//        String rootDir = MMKV.initialize(dir);

        testMMKV(rootDir);
    }

    private void testMMKV(String rootDir) {

        System.out.println("默认存储地址 mmkv root: " + rootDir);
        MMKV kv = MMKV.defaultMMKV();

        kv.encode("isOpen", true);
        boolean isOpen = kv.decodeBool("isOpen");

        kv.encode("volume", Integer.MIN_VALUE);
        int volume = kv.decodeInt("volume");

        kv.encode("name", "zhangsan");
        String name = kv.decodeString("name");

        kv.encode("device", new Device("", 1, ""));//mmkv 存对象，对象要实现parcelable接口

        System.out.println("获取 mmkv 值: " + " isOpen = " + isOpen + " volume = " + volume + " name = " + name);
    }

    private void initXLog() {
//        https://github.com/elvishew/xLog/blob/master/README_ZH.md


//        String logPath = this.getFilesDir().getAbsolutePath() + "/xlog";
//          /data/user/0/com.zz.zzwebrtc/files/xlog   android11 无法直接在Device File Explorer中查看
        String logPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/xlogtest/logs";
//          /storage/emulated/0/xlogtest/logs   android10  无法创建目录？
        LogConfiguration config = new LogConfiguration.Builder()
                .logLevel(LogLevel.ALL)
//                .logLevel(BuildConfig.DEBUG ? LogLevel.ALL : LogLevel.WARN)
//                .enableThreadInfo()  //打印线程信息
                .enableStackTrace(5)  //打印引用链
                .enableBorder()  //打印界限
                .build();
        Printer androidPrinter = new AndroidPrinter(true);
        Printer filePrinter = new FilePrinter
                .Builder(logPath)
                .fileNameGenerator(new DateFileNameGenerator())
                .backupStrategy(new NeverBackupStrategy())
                .build();
        XLog.init(config, androidPrinter, filePrinter);
        XLog.i(logPath);
//        XLog.init(LogLevel.ALL);   //简单方式初始化
//        默认打印效果
//        2022-05-12 14:15:01.578 24632-24632/com.example.zz.example I/X-LOG: ╔═══════════════════════════════════════════════════════════════════════════════════════════════════
//        2022-05-12 14:15:01.578 24632-24632/com.example.zz.example I/X-LOG: ║手机型号:TX20-A10-AIHome
//        2022-05-12 14:15:01.578 24632-24632/com.example.zz.example I/X-LOG: ║系统版本:9
//        2022-05-12 14:15:01.578 24632-24632/com.example.zz.example I/X-LOG: ║产品型号:AIPad
//        2022-05-12 14:15:01.578 24632-24632/com.example.zz.example I/X-LOG: ║版本显示:iFLY_V1.01.3
//        2022-05-12 14:15:01.578 24632-24632/com.example.zz.example I/X-LOG: ║系统定制商:iFLYTEK
//        2022-05-12 14:15:01.578 24632-24632/com.example.zz.example I/X-LOG: ║设备参数:IFLYTEKCB
//        2022-05-12 14:15:01.578 24632-24632/com.example.zz.example I/X-LOG: ║开发代号:REL
//        2022-05-12 14:15:01.578 24632-24632/com.example.zz.example I/X-LOG: ║SDK版本号:28
//        2022-05-12 14:15:01.578 24632-24632/com.example.zz.example I/X-LOG: ║CPU类型:arm64-v8a
//        2022-05-12 14:15:01.578 24632-24632/com.example.zz.example I/X-LOG: ║硬件类型:tx20
//        2022-05-12 14:15:01.578 24632-24632/com.example.zz.example I/X-LOG: ║主机:ubuntu-sz
//        2022-05-12 14:15:01.578 24632-24632/com.example.zz.example I/X-LOG: ║生产ID:PPR1.180610.011
//        2022-05-12 14:15:01.578 24632-24632/com.example.zz.example I/X-LOG: ║ROM制造商:IFLYTEK
//        2022-05-12 14:15:01.578 24632-24632/com.example.zz.example I/X-LOG: ╚══════════════════════════════════════════

    }


    private void initLog() {
        FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
                .showThreadInfo(false)  // 是否显示线程信息，默认为ture
                .methodCount(0)         // 显示的方法行数，默认为2
                .methodOffset(7)        // 隐藏内部方法调用到偏移量，默认为5
                //.logStrategy(customLog) // 更改要打印的日志策略。
                .tag("Zz")   // 每个日志的全局标记。默认PRETTY_LOGGER
                .build();

        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy));

        Logger.addLogAdapter(new AndroidLogAdapter() {
            @Override
            public boolean isLoggable(int priority, String tag) {
                return BuildConfig.DEBUG;
            }
        });

        //日志保存到本地sd卡，保存位置为：(logger 框架无法指定日志存储路径，xlog可以)
        //                String diskPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        //                String folder = diskPath + File.separatorChar + "logger";
        Logger.addLogAdapter(new DiskLogAdapter());


        //打印方法
        Logger.d("debug");
        Logger.e("error");
        Logger.w("warning");
        Logger.v("verbose");
        Logger.i("information");
        Logger.wtf("wtf!!!!");


        //打印集合
//        Logger.d(MAP);
//        Logger.d(SET);
//        Logger.d(LIST);
//        Logger.d(ARRAY);

        //打印json
//        Logger.json(JSON_CONTENT);
    }

}
